module.exports = async function(param) {

	/**
	 * 先检查数据是否齐全和规范，这可能也可以作为阻拦机器码的一种方式吧
	 * 还需要增加验证内容，如手机格式验证
	 */
	if (!param.organization || !param.realname || !param.mobile) {

		return {
			errCode: 0,
			errMsg: '数据不全或格式错误',
		}
	}

	const dbJQL = uniCloud.databaseForJQL({ // 获取JQL database引用，此处需要传入云对象的clientInfo
		clientInfo: this.clientInfo
	})

	// 设置当前用户临时管理员权限
	dbJQL.setUser({
		// uid:user.uid,
		role: ['admin']
	})
	let organ_id = ''
	let euid = ''
	let userCheck = null


	//应先检查是否已报名过，同时取得机构和人员信息数据
	let organCheck = await dbJQL.collection('tian-event-organization').where({
		original: param.organization
	}).field('original').get()

	if (organCheck.data.length > 0) {
		organ_id = organCheck.data[0]._id

		userCheck = await dbJQL.collection('tian-event-users').where(
			`organization_id=='${organ_id}' && realname == '${param.realname}' && mobile == '${param.mobile}' `
		).field('position').get()

		if (userCheck.data.length > 0) {
			euid = userCheck.data[0]._id
		}
	}
	
	let regisCheck = null;
	// 检查当前活动是否已报过名,防止重复报名
	if (organ_id && euid) {
		regisCheck = await dbJQL.collection('tian-event-registration').where({
			event_id: param.event_id,
			organization_id: organ_id,
			euid: euid
		}).get()
		
		if (regisCheck.data.length > 0) {
			return {
				errCode: 0,
				errMsg: '重复提交报名数据'
			}
		}
	}

	if (organCheck.data.length === 0) {
		// 提取机构参数
		let organizationParam = {
			original: param.organization,
			lang: param.lang
		}
		organRes = await dbJQL.collection('tian-event-organization').add(organizationParam)
		organ_id = organRes.id
	}
	
	if (!userCheck || userCheck.data.length === 0) {
		let userPara = {
			realname: param.realname,
			lang: param.lang,
			mobile_confirmed: 1,
			gender: param.gender,
			country_code: param.country_code,
			mobile: param.mobile,
			email: param.email || '',
			organization_id: organ_id,
			position: param.position || '',
		}
		let userRes = await dbJQL.collection('tian-event-users').add(userPara)
		euid = userRes.id
	} else {
		// euid = userCheck.data[0]._id
		// if (param.position && (param.position != userCheck.data[0].position||'')) {
		// 	await await dbJQL.collection('tian-event-users').doc(euid).update({
		// 		position: param.position
		// 	})
		// }
		// 重新保存性别和职务，因这两项可能会发生改变
		await await dbJQL.collection('tian-event-users').doc(euid).update({
			position: param.position,
			gender:param.gender
		})
	}

	let regisPara = {
		event_id: param.event_id,
		organization_id: organ_id,
		euid: euid,
		lang: param.lang
	}
	let eventRegis = await dbJQL.collection('tian-event-registration').add(regisPara)

	return {
		errCode: 0,
		errMsg: 'test-success'
	}
}